/**
 * Copyright 2006 Van de Wijgerd B.V. All rights reserved.
 */
package com.googlecode;

import org.apache.commons.httpclient.*;
import org.apache.commons.httpclient.auth.AuthScope;
import org.apache.commons.httpclient.cookie.CookiePolicy;

import java.io.IOException;

public class DefaultHttpConImpl implements HttpCon {
    private HttpClient httpClient;

    public DefaultHttpConImpl(HttpClient httpClient) {
        this.httpClient = httpClient;
    }

    public String execute(HttpMethod method, AuthScope authScope,Credentials credentials) throws ApiException {
        method.getParams().setCookiePolicy(CookiePolicy.BROWSER_COMPATIBILITY);

        try {
            int statusCode;
            if (credentials != null) {
                HttpState state = new HttpState();
                httpClient.getParams().setAuthenticationPreemptive(true);
                state.setCredentials(authScope, credentials);
                statusCode = httpClient.executeMethod(null, method, state);
            } else {
                statusCode = httpClient.executeMethod(method);
            }
            if (statusCode != HttpStatus.SC_OK) {
                String error = String.format("Expected 200 OK. Received %d %s", statusCode, HttpStatus.getStatusText(statusCode));
                throw new ApiException(statusCode,error);
            }
            String responseBody = method.getResponseBodyAsString();
            if (responseBody == null) {
                throw new ApiException(statusCode,"Expected response body, got null");
            }
            return responseBody;
        } catch (HttpException e) {
            throw new ApiException(e);
        } catch (IOException e) {
            throw new ApiException(e);
        } finally {
            method.releaseConnection();
        }
    }
}
